package sky.cin.framework.config;

import org.yaml.snakeyaml.Yaml;
import sky.cin.framework.log.Croog;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class YamlUtils implements ConfigFile {
    
    private Croog log;
    
    private String fileName;
    
    private Object temp;
    
    public YamlUtils(String fileName) {
        log = new Croog("sky.cin.framework.config.YamlUtils");
        this.fileName =fileName;
        load();
    }
    
    private void load() {
        Yaml yaml = new Yaml();
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(this.fileName);
        try {
            this.temp = yaml.load(inputStream);
        } catch (Exception e) {
            log.error("未定义的配置文件: " + fileName);
            System.exit(1);
        }
        log.info("已加载配置文件: " + fileName);
    }
    
    private Map<Object, Object> getMap()  {
        if(this.temp instanceof  Map){
            return (Map<Object, Object>)this.temp;
        }
        return null;
    }
    
    private List<Object> getList()  {
        if(this.temp instanceof  List){
            return (List<Object>)this.temp;
        }
        return null;
    }
    
    public Object get(String keys) {
        Map<Object, Object> map = getMap();
        List<Object> list = getList();
        Object value = null;
        keys = keys.replace("[", ".[");
        for (String key : keys.split("\\.")) {
            value = map == null
                ? list.get(getIndex(key))
                : map.get(key);
            if (value == null) {
                break;
            }
            if (value instanceof List) {
                list = (List<Object>) value;
                map = null;
            }
            if (value instanceof Map) {
                map = (Map<Object, Object>) value;
                list = null;
            }
        }
        return value;
    }
    
    private Integer getIndex(String key) {
        return Integer.parseInt(key.substring(1, key.length() - 1));
    }
    
    public String getString(String keys) {
        Object value = get(keys);
        return value == null ? null : value.toString();
    }
    
    public Integer getInteger(String keys) {
        String string = getString(keys);
        return string != null ? Integer.parseInt(string) : null;
    }
    
    public Float getFloat(String keys) {
        String string = getString(keys);
        return string != null ? Float.parseFloat(string) : null;
    }
    
    public Map<Object, Object> getMap(String keys) {
        Object obj = get(keys);
        if (obj instanceof Map) {
            return (Map<Object, Object>) obj;
        }
        return null;
    }
    
    public List<Object> getList(String keys) {
        Object obj = get(keys);
        if (obj instanceof List) {
            return (List<Object>) obj;
        }
        return null;
    }
    
}

